//
//  UIImage+SJBGColor.swift
//  Employee
//
//  Created by swordjoy on 2017/3/30.
//  Copyright © 2017年 remotevillage. All rights reserved.
//

import Foundation
import UIKit

extension UIImage {
  
    // 适配屏幕
    // 宽设为屏幕宽
    // 按比例算出高
    var previewSize: CGSize {
        let width = UIScreen.width
        let height = self.size.height * ( width / self.size.width )
        return CGSize(width: width, height: height)
    }
    
    // 直接根据previewSize强行绘制新的image
    // 一般不用,让UIImageView自己根据previewSize fill
    var previewImage: UIImage? {
        let temp = self.resizeImage(to: self.previewSize)
        return temp
    }

    func resizeImage(to newSize: CGSize) -> UIImage? {
        UIGraphicsBeginImageContextWithOptions(newSize, true, UIScreen.main.scale)
        self.draw(in: CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height))
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return newImage
    }
    static func getLinerGradientImage(with startColor: UIColor, endColor: UIColor, size: CGSize) -> UIImage {
        
        UIGraphicsBeginImageContext(size)
        let gc = UIGraphicsGetCurrentContext()
        //创建CGMutablePathRef
        let path = CGMutablePath()
        //绘制Path
        let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
        path.addRect(rect)
        path.closeSubpath()
        //绘制渐变
        drawLinearGradient(with: gc!, path: path, startColor: startColor.cgColor, endColor: endColor.cgColor)
        //注意释放CGMutablePathRef
        
        //从Context中获取图像，并显示在界面上
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        
        return image!
    }
    static func drawLinearGradient(with context: CGContext, path: CGPath, startColor: CGColor, endColor: CGColor) {
        
        let colorSpace = CGColorSpaceCreateDeviceRGB()
        let locations: [CGFloat] = [0.0, 1.0]
        let colors: [Any]? = [(startColor as Any), (endColor as Any)]
        let gradient = CGGradient(colorsSpace: colorSpace, colors: (colors as CFArray?)!, locations: locations)
        let pathRect = path.boundingBox
        //具体方向可根据需求修改
        let startPoint = CGPoint(x: CGFloat(pathRect.minX), y: CGFloat(pathRect.midY))
        let endPoint = CGPoint(x: CGFloat(pathRect.maxX), y: CGFloat(pathRect.midY))
        context.saveGState()
        context.addPath(path)
        context.clip()
        context.drawLinearGradient(gradient!, start: startPoint, end: endPoint, options: [])
        context.restoreGState()
    }
  static func getImage(with color: UIColor) -> UIImage {
    
    let rect = CGRect(x: CGFloat(0.0), y: CGFloat(0.0), width: CGFloat(1.0), height: CGFloat(1.0))
    UIGraphicsBeginImageContext(rect.size)
    let context: CGContext? = UIGraphicsGetCurrentContext()
    context?.setFillColor(color.cgColor)
    context?.fill(rect)
    let image  = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return image!
    
  }
  
  func thumbnailSquareOriginalScale(with width: CGFloat) -> UIImage {
    let oldSize = self.size
    var rect = CGRect.zero
    if oldSize.width > oldSize.height {
      rect.size.width = oldSize.width * width / oldSize.height
      rect.size.height = width
      rect.origin.x = 0
      rect.origin.y = 0
    }
    else {
      rect.size.width = width
      rect.size.height = oldSize.height * width / oldSize.width
      rect.origin.x = 0
      rect.origin.y = 0
    }
    
    UIGraphicsBeginImageContext(rect.size)
    let context = UIGraphicsGetCurrentContext()
    context!.setFillColor(UIColor.clear.cgColor)
    UIRectFill(rect)
    self.draw(in: rect)
    let image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    
    return image!
    
  }
    
    
    var uploadData: Data {
        let data = UIImageJPEGRepresentation(uploadImage, 0.5)!
        return data
    }
    
    /*
     据说仿照微信
     宽高均 <= 1280，图片尺寸大小保持不变
     宽或高 > 1280 && 宽高比 <= 2，取较大值等于1280，较小值等比例压缩
     宽或高 > 1280 && 宽高比 > 2 && 宽或高 < 1280，图片尺寸大小保持不变
     宽高均 > 1280 && 宽高比 > 2，取较小值等于1280，较大值等比例压缩
     */
    var uploadSize: CGSize {
        var width = self.size.width
        var height = self.size.height
        
        let boundary: CGFloat = 1280
        
        // 宽高均 <= 1280，图片尺寸大小保持不变
        guard width > boundary || height > boundary else {
            return CGSize(width: width, height: height)
        }
        
        let s = max(width, height) / min(width, height)
        // 宽高比 <= 2
        if s <= 2 {
            // 取较大值等于1280，较小值等比例压缩
            let x = max(width, height) / boundary
            if width > height {
                width = boundary
                height = height / x
            } else {
                height = boundary
                width = width / x
            }
        }
        // 宽高比 > 2
        else {
            // 取较小值等于1280，较大值等比例压缩
            if min(width, height) >= boundary {
                // 取较小值等于1280，较大值等比例压缩
                let x = min(width, height) / boundary
                if width < height {
                    width = boundary
                    height = height / x
                } else {
                    height = boundary
                    width = width / x
                }
            }
        }
        return CGSize(width: width, height: height)
    }
    
    // 这里变相调整了图片的方向
    var uploadImage: UIImage {
        UIGraphicsBeginImageContextWithOptions(uploadSize, false, self.scale)
        let rect = CGRect(x: 0, y: 0, width: uploadSize.width, height: uploadSize.height)
        self.draw(in: rect)
        let upImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return upImage!
    }

}
